package com.yunsuo.bean;

import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;

public class Identify {

    private static Connection getConn() {
        String driver = "com.mysql.cj.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/raspberry?characterEncoding=UTF-8";
        String username = "root";
        String password = "123456";
        Connection conn = null;
        try {
            Class.forName(driver); //classLoader,加载对应驱动
            conn = (Connection) DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    public static int findFinger(String str1){
        Connection conn = getConn();
        //int i = 0;
        String sql = "select * from fingerprint_raspberry";
        PreparedStatement pstmt;
        try {
            pstmt = (PreparedStatement)conn.prepareStatement(sql);
            ResultSet rs = pstmt.executeQuery();
            int col = rs.getMetaData().getColumnCount();
            //System.out.println("============================");
            while (rs.next()) {
//                for (int i = 1; i <= col; i++) {
//                    //System.out.print(rs.getString(i) + "\t");
//                    if ((i == 2) && (rs.getString(i).length() < 8)) {
//                        //System.out.print("\t");
//                    }
//                }
//                //System.out.println("");
                String content=rs.getString(6);
                //System.out.println("str1==="+str1);
                String[] outString = content.split("/");
                String position=outString[outString.length-1];
                //System.out.println("position=="+position);
//                //System.out.println("content="+content.substring(21,23));
                if(position.equals(str1)){
                    //调用开门的python代码
                    if(rs.getString(7).equals("0")){
                        Process ps = null;
                        //System.out.println("use open.py");
                        ////System.out.println("open.py");
                        ps = Runtime.getRuntime().exec("python3 "+ "/home/pi/openDoor/open.py");
                        int status1 = ps.waitFor();//返回0为成功
                        //System.out.println(status1);
                        //System.out.println("open success");
                        Thread.sleep(200);
                        //System.out.println("开门后2秒延时结束");
                        final HttpConnectionFinal httpConnection = new HttpConnectionFinal();
                        String lockID=rs.getString("f_lock_id");
                        String userID=rs.getString("f_user_id");
                        Map<String,Object> map=new HashMap<>();
                        map.put("dLockId",lockID);
                        map.put("dUserId",userID);
                        String jsonString = JSONObject.toJSONString(map);
                        String info="info="+jsonString;
                        httpConnection.connection("/raspberry/addRecord", info);
                    }else if(rs.getString(7).equals("1")){
                        Process ps1 = null;
                        //System.out.println("use speek.py");
                        ////System.out.println("open.py");
                        try {
                            ps1 = Runtime.getRuntime().exec("python3 "+ "/home/pi/openDoor/speed.py");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        //System.out.println("finger is delete");
                    }
                }
            }
            //System.out.println("============================");

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }


    public static void search(){
        Process ps = null;
        //String[] args = new String[] { "python3","/home/pi/Door/fingerSplit/ValidTemple.py",path};
        try {
            ps = Runtime.getRuntime().exec("python3 "+ "/home/pi/Door/fingerSplit/Identify.py");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //Process process = Runtime.getRuntime().exec("python3 ValidTemple.py",path);
//            process.waitFor();
        InputStreamReader ir = new InputStreamReader(ps.getInputStream());
        LineNumberReader input = new LineNumberReader(ir);
        String str="";
        String str1="";
        int flag=1;//当python返回为OK字段时，说明搜索到了指纹。将flag=0，若返回NO字段，说明未搜索到，flag=1
        while (true) {
            try {
                if (!((str = input.readLine()) != null)) break;
            } catch (IOException e) {
                e.printStackTrace();
            }
            if(str.equals("OK")){
                //System.out.println("kkkkkkkkk");
                flag=0;
            }else if(str.equals("NO")){
                //System.out.println("nnnnnnnnn");
                flag=1;
            }
            ////System.out.println("python输出="+str);
            str1=str;
        }
        int status1 = 0;//返回0为成功
        try {
            status1 = ps.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //System.out.println("str========="+str1);
        //到数据库中查找指纹信息
        if(flag==0){
            findFinger(str1);
        }
        else{
//            Process ps1 = null;
//            //System.out.println("use speek.py");
//            ////System.out.println("open.py");
//            try {
//                ps1 = Runtime.getRuntime().exec("python3 "+ "/home/pi/openDoor/speed.py");
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
        }


//            result = input.readLine();
//            //System.out.println("result=="+result);

        //System.out.println(status1);
        try {
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            ir.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
